#include "stdafx.h"
#include "question.h"

QUESTION::QUESTION(void)
{
	nQuestion = 0;
	data.empty();
}

QUESTION::~QUESTION(void)
{
	for (vector<PQUESINFOR>::iterator p = data.begin();
		p != data.end(); p++)
		delete (*p);
}

// Add a question to question bank
bool QUESTION::AddQuestion(PQUESINFOR pQuestion) {
	if (data.size() >= data.max_size()) {
		return false;
	}

	nQuestion++;
	data.push_back(pQuestion);

	return true;
}

// Open fName data file
bool QUESTION::OpenDataFile(char *fName) {
	fData.open(fName, ios::in);

	if (fData && Utf8FileCheck(fData))
		return true;

	// Not open file or the file is not UTF8
	return false;
}

// The number of questions
int QUESTION::NoQuestion() {
	return nQuestion;
}

// Read one by one a question from the data file
PQUESINFOR QUESTION::ReadQuestion() {
	// The first call, we must ignore 3 first bytes
	static int pos = 3;

	PQUESINFOR pQuestion = new QUESINFOR;
	
	const int MaxLen = 1000;
	char buffer[MaxLen] = "";

	fData.seekg(pos);
	
	// Get a question
	while(fData.getline(buffer, MaxLen) && *buffer != '@');
	if (!fData.eof()) {
		pQuestion->question = Utf8ToWchar(buffer + 1);

		// Get one by one choices
		for (int i = 0; i < 4; i++) {
			while(fData.getline(buffer, MaxLen) && *buffer != '~')
				if (*buffer == '@') {
					pos = fData.tellg();
					pos = pos - strlen(buffer) - 2;
					delete pQuestion;
					return ReadQuestion();	// Read next question
				}

			if (fData.eof()) {
				delete pQuestion;
				return NULL;
			}

			pQuestion->choice.push_back(Utf8ToWchar(buffer + 1));
		}

		// Get answer
		while(fData.getline(buffer, MaxLen) && *buffer != '#')
			if (*buffer == '@') {
				pos = fData.tellg();
				pos = pos - strlen(buffer) - 2;
				delete pQuestion;
				return ReadQuestion();	// Read next question
			}

		if (*buffer == '#') {
			pQuestion->answer = atoi(buffer + 1) - 1;
		
			if (pQuestion->answer < 0 || pQuestion->answer > 3) {
				pos = fData.tellg();
				delete pQuestion;
				return ReadQuestion();	// Read next question
			}
			else {
				pos = fData.tellg();
				return pQuestion;
			}
		}
	}

	delete pQuestion;
	return NULL;
}

// Load all questions from file
bool QUESTION::LoadData() {
	PQUESINFOR pQuestion = NULL;
	while ((pQuestion = ReadQuestion()) != NULL)
		AddQuestion(pQuestion);

	if (nQuestion)
		return true;

	return false;
}

PQUESINFOR & QUESTION::operator [](int i) {
	return data[i];
}